#include"UnitControlerManager.h"

#include"UnitControlerBaseClass.h"
#include"DroneControler.h"
#include"ZerglingControler.h"
#include"HydraliskControler.h"
#include"ProductionTask.h"

void UnitControlerManagerClass::OnFrame()
{
	for(map<Unit* , UnitControlerBaseClass*>::iterator it = _unitControlers.begin() ; it != _unitControlers.end() ; )
	{
		Unit* whichUnit(it->first);
		_unitControlers[whichUnit]->OnFrame();
		if(_unitControlers[whichUnit]->ShouldRemove())
		{
			_unitControlers.erase(it++);
		}
		else
		{
			++it;
		}
	}

	const set<Unit*>& allUnits = Broodwar->self()->getUnits();
	for(set<Unit*>::const_iterator it = allUnits.begin() ; it != allUnits.end() ; ++it)
	{
		Unit* whichUnit(*it);
		map<Unit* , UnitControlerBaseClass*>::iterator controlerIterator = _unitControlers.find(whichUnit);
		if(controlerIterator == _unitControlers.end())
		{
			UnitControlerBaseClass* newControler(CreateControler(whichUnit));
			if(newControler != NULL)
			{
				_unitControlers[whichUnit] = newControler;
			}
		}
	}
}
void UnitControlerManagerClass::OnUnitCreate(Unit* unit)
{
	const UnitType& unitType(unit->getType());
	if(unitType == UnitTypes::Zerg_Larva)
	{
	}
}
void UnitControlerManagerClass::OnUnitMorph(Unit* unit)
{
}
void UnitControlerManagerClass::Build(ProductionTask& buildTask)
{
	for each(Unit* whichUnit in Broodwar->self()->getUnits())
	{
		if(whichUnit->getType() == UnitTypes::Zerg_Drone)
		{
			DroneControler* droneControler = (DroneControler*)(_unitControlers[whichUnit]);
			if(droneControler->GetState() == DroneControler::Mining)
			{
				droneControler->Build(buildTask);
				break;
			}
		}
	}
}
UnitControlerBaseClass* UnitControlerManagerClass::GetControler(Unit* unit)
{
	if(_unitControlers[unit] == NULL)
	{
		UnitControlerBaseClass* newControler(CreateControler(unit));
		if(newControler != NULL)
		{
			_unitControlers[unit] = newControler;
		}
	}
	return _unitControlers[unit];
}
UnitControlerBaseClass* UnitControlerManagerClass::CreateControler(Unit* unit)
{
	if(unit->getType() == UnitTypes::Zerg_Drone)
	{
		return new DroneControler(unit);
	}
	else if(unit->getType() == UnitTypes::Zerg_Zergling)
	{
		return new ZerglingControler(unit);
	}
	else if(unit->getType() == UnitTypes::Zerg_Hydralisk)
	{
		return new HydraliskControler(unit);
	}
	return NULL;
}